# Makefile for tds4py - Compiling Fortran code and creating Python module

# Fortran编译器
FC = gfortran
pwd = /home/shi/data16T/Coda_HSR/libs/tds/src25
# 编译选项
FFLAGS = -O2 -fPIC -free

# 创建build目录用于存放目标文件和模块文件
BUILD_DIR = build
BIN_DIR = bin

# 源文件
FORTRAN_MODULES = constants.f90 parameters.f90 matrix_operations.f90 basic.f90 grt_coefficients.f90 wavefield_calculation.f90 input_output.f90

# 目标文件路径在build目录中
FORTRAN_OBJS = $(addprefix $(BUILD_DIR)/, $(FORTRAN_MODULES:.f90=.o))
FORTRAN_OBJS_WITH_TDS = $(FORTRAN_OBJS)

TARGET = main
MAIN_TARGET = main

# 默认目标
all: $(BUILD_DIR) $(TARGET)

# 创建build目录
$(BUILD_DIR):
	mkdir -p $(BUILD_DIR)

# 编译Fortran目标文件到build目录
$(BUILD_DIR)/%.o: %.f90
	$(FC) $(FFLAGS) -J$(BUILD_DIR) -c $< -o $@

# 编译为可执行文件用于测试
main: $(FORTRAN_OBJS) $(BUILD_DIR)/main.o
	$(FC) $(FFLAGS) -o $(MAIN_TARGET) $(FORTRAN_OBJS) $(BUILD_DIR)/main.o
	

# 使用传统的distutils后端构建Python模块（避免Python 3.12中f2py默认使用meson的问题）
python: $(FORTRAN_OBJS) tds4py.f90
	# f2py -c   tds4py.f90 $(FORTRAN_OBJS) -m tds4py -I$(pwd) --build-dir ./tmp1
	# 只能py3.11构建
	f2py -c   tds4py.f90 $(FORTRAN_OBJS) -m tds4py -I$(BUILD_DIR) --build-dir ./tmp2 --backend distutils
	mv *.so ./python


$(BUILD_DIR)/main.o: main.f90
	$(FC) $(FFLAGS) -J$(BUILD_DIR) -c main.f90 -o $@

# 依赖关系
$(BUILD_DIR)/constants.o: constants.f90
	$(FC) $(FFLAGS) -J$(BUILD_DIR) -c constants.f90 -o $@

$(BUILD_DIR)/parameters.o: parameters.f90 $(BUILD_DIR)/constants.o
	$(FC) $(FFLAGS) -J$(BUILD_DIR) -c parameters.f90 -o $@

$(BUILD_DIR)/matrix_operations.o: matrix_operations.f90 $(BUILD_DIR)/constants.o
	$(FC) $(FFLAGS) -J$(BUILD_DIR) -c matrix_operations.f90 -o $@

$(BUILD_DIR)/basic.o: basic.f90 $(BUILD_DIR)/parameters.o $(BUILD_DIR)/constants.o
	$(FC) $(FFLAGS) -J$(BUILD_DIR) -c basic.f90 -o $@

$(BUILD_DIR)/grt_coefficients.o: grt_coefficients.f90 $(BUILD_DIR)/parameters.o $(BUILD_DIR)/matrix_operations.o
	$(FC) $(FFLAGS) -J$(BUILD_DIR) -c grt_coefficients.f90 -o $@

$(BUILD_DIR)/wavefield_calculation.o: wavefield_calculation.f90 $(BUILD_DIR)/parameters.o $(BUILD_DIR)/matrix_operations.o $(BUILD_DIR)/grt_coefficients.o
	$(FC) $(FFLAGS) -J$(BUILD_DIR) -c wavefield_calculation.f90 -o $@

$(BUILD_DIR)/input_output.o: input_output.f90 $(BUILD_DIR)/parameters.o
	$(FC) $(FFLAGS) -J$(BUILD_DIR) -c input_output.f90 -o $@

$(BUILD_DIR)/tds4py.o: tds4py.f90
	$(FC) $(FFLAGS) -J$(BUILD_DIR) -c tds4py.f90 -o $@

$(BUILD_DIR)/tds4py_simple.o: tds4py_simple.f90
	$(FC) $(FFLAGS) -J$(BUILD_DIR) -c tds4py_simple.f90 -o $@

# 清理目标文件
clean:
	rm -f $(BUILD_DIR)/*.o $(BUILD_DIR)/*.mod

# 清理所有生成的文件
distclean: clean
	rm -rf $(BUILD_DIR)
	rm -f $(TARGET) $(TARGET_SIMPLE) $(MAIN_TARGET)

# 运行测试
test: $(TARGET)
	$(PYTHON) tds4py.py

.PHONY: all clean distclean test main simple python python-old python-meson python-simple